#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <jsoncpp/json/json.h>
#include <mutex>
#include <cassert>
#include <fstream>
#include <algorithm>

#include "oj_model_db.hpp"
#include "oj_view.hpp"
#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "../comm/httplib.h"

namespace ns_control
{
    using namespace ns_model;
    using namespace ns_view;
    using namespace ns_log;
    using namespace ns_util;
    using namespace httplib;

    // 主机
    class Machine
    {
    public:
        string ip;
        int port;
        std::mutex *mtx;

    private:
        uint64_t load; // 负载

    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine() {}

        // 返回: a.load<b.load
        bool operator<(const Machine &m)
        {
            return load < m.load;
        }

        // 主机负载++
        void IncLoad()
        {
            if (mtx)
            {
                mtx->lock();
            }
            load++;
            if (mtx)
            {
                mtx->unlock();
            }
        }
        // 主机负载--
        void DecLoad()
        {
            if (mtx)
            {
                mtx->lock();
            }
            load--;
            if (mtx)
            {
                mtx->unlock();
            }
        }
        // 主机负载清零
        void ResetLoad()
        {
            if (mtx)
            {
                mtx->lock();
            }
            load = 0;
            if (mtx)
            {
                mtx->unlock();
            }
        }
        // 获取主机负载
        uint64_t GetLoad()
        {
            uint64_t _load = 0;
            if (mtx)
            {
                mtx->lock();
            }
            _load = load;
            if (mtx)
            {
                mtx->unlock();
            }
            return _load;
        }
    };

    const string service_machine = "./conf/service_machine.conf";
    // 负载均衡模块
    class LoadBlance
    {
    private:
        // 下标作为主机id
        std::vector<Machine> machines;
        // 在线主机id
        std::vector<int> online;
        // 离线主机id
        std::vector<int> offline;

        std::mutex mtx;

    public:
        LoadBlance()
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载:" << service_machine << "成功\n";
        }
        ~LoadBlance() {}
        bool LoadConf(const string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载:" << machine_conf << "失败\n";
                return false;
            }
            string line = "";
            while (getline(in, line))
            {
                std::vector<string> tokens;
                StringUtil::SplitString(&tokens, line, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "切分:" << line << "失败\n";
                    continue;
                }
                Machine machine;
                machine.ip = tokens[0];
                machine.port = std::stoi(tokens[1]);
                machine.mtx = new std::mutex;

                online.push_back(machines.size());
                machines.push_back(machine);
            }

            in.close();
            return true;
        }

        /*************************
         * 轮询
         * id: 输出型 主机编号
         * machine: 输出型 主机地址
         * ***********************/
        bool SmartChoice(int *id, Machine **machine)
        {
            mtx.lock();

            if (online.empty())
            {
                mtx.unlock();
                LOG(FATAL) << "主机均离线,没有可用主机\n";
                return false;
            }

            int min_load_id = online[0];
            for (auto current_id : online)
            {
                if (machines[current_id] < machines[min_load_id])
                {
                    min_load_id = current_id;
                }
            }
            *id = min_load_id;
            *machine = &machines[min_load_id];

            mtx.unlock();
            return true;
        }
        // 所有主机统一上线
        void OnlineMachine()
        {
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.empty();
            mtx.unlock();
            LOG(INFO) << "成功上线所有主机\n";
        }
        // 离线which_id的主机
        void OfflineMachine(const int which_id)
        {
            mtx.lock();
            auto iter = std::find(online.begin(), online.end(), which_id);
            if (iter != online.end())
            {
                machines[which_id].ResetLoad();
                online.erase(iter);
                offline.push_back(which_id);
            }
            mtx.unlock();
        }
        // 测试
        void ShowMachine()
        {
            mtx.lock();
            std::cout << "在线主机: ";
            for (auto m : online)
            {
                std::cout << m << " ";
            }
            std::cout << "\n离线主机: ";
            for (auto m : offline)
            {
                std::cout << m << " ";
            }
            std::cout << "\n";
            mtx.unlock();
        }
    };

    class Control
    {
    private:
        Model _model;
        View _view;
        LoadBlance _load_blance;

    public:
        Control() {}
        ~Control() {}
        void RecoverMachine()
        {
            _load_blance.OnlineMachine();
        }
        bool AllQuestions(string *html)
        {
            std::vector<Question> questions;
            if (_model.GetAllQuestions(&questions))
            {
                // 获取题目成功,构建网页
                // 构建失败
                if (!_view.AllRenderHTML(questions, html))
                {
                    return false;
                }
            }
            else
            {
                *html = "题目列表生成失败";
                return false;
            }
            return true;
        }
        bool NumQuestion(const string &number, string *html)
        {
            Question question;
            if (_model.GetNumQuestion(number, &question))
            {
                // 获取题目成功,构建网页
                // 构建失败
                if (_view.OneRenderHTML(question, html))
                {
                    return false;
                }
            }
            else
            {
                *html = "题目:" + number + "不存在";
                return false;
            }
            return true;
        }
        void Judge(const string &number, const string &in_json, string *out_json)
        {
            // 根据题号获取题目
            Question q;
            _model.GetNumQuestion(number, &q);
            // 对in_json反序列化
            Json::Value in_val;
            Json::Reader reader;
            reader.parse(in_json, in_val);
            // 拼接用户代码和测试代码
            Json::Value compile_val;
            compile_val["input"] = in_val["input"].asString();
            compile_val["code"] = in_val["code"].asString() + "\n" + q.tail;
            compile_val["cpu_limit"] = q.cpu_limit;
            compile_val["mem_limit"] = q.mem_limit;
            Json::StyledWriter writer;
            string compile_string = writer.write(compile_val);
            // 选择主机
            while (true)
            {
                int id = 0;
                Machine *machine = nullptr;
                // 没有可用主机
                if (!_load_blance.SmartChoice(&id, &machine))
                {
                    break;
                }
                // 发起http请求
                Client cli(machine->ip, machine->port);
                machine->IncLoad();
                LOG(INFO) << "已选择主机id: " << id << " 详情: " << machine->ip << ":" << machine->port << " 负载:" << machine->GetLoad() << "\n";
                if (auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=UTF-8;"))
                {
                    // 请求完成,负载减少
                    machine->DecLoad();
                    // 请求成功,将结果赋值给out_json
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        LOG(INFO) << "编译运行服务请求成功...\n";
                        break;
                    }
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << "当前主机id: " << id << " 详情: " << machine->ip << ":" << machine->port << "可能已离线\n";
                    _load_blance.OfflineMachine(id);
                    _load_blance.ShowMachine();
                }
            }
        }
    };
}